package pkg

import (
	"github.com/gofiber/fiber/v2"
	"github.com/urfave/cli/v2"
	"gopkg.in/yaml.v3"
	"gorm.io/gorm"
	"io/ioutil"
)

type JwtConfig struct {
	TokenSecret string `yaml:"tokenSecret"`
	Ext         int    `yaml:"ext"`
}

type DbConfig struct {
	Username string `yaml:"username"`
	Password string `yaml:"password"`
	Host     string `yaml:"host"`
	Port     string `yaml:"port"`
	Database string `yaml:"database"`
	Charset  string `yaml:"charset"`
	Location string `yaml:"location"`
}

type ServerConfig struct {
	Port string `yaml:"port"`
	Host string `yaml:"host"`
}

type AppConfig struct {
	Key              string               `yaml:"key"`
	ClosedRequests   []fiber.Handler      `yaml:"-"`
	BeforeStartServe BeforeStartServeFunc `yaml:"-"`
}

type BeforeStartServeFunc func()

type Config struct {
	JwtConfig    JwtConfig    `yaml:"jwt"`
	DbConfig     DbConfig     `yaml:"db"`
	ServerConfig ServerConfig `yaml:"server"`
	GormDb       *gorm.DB     `yaml:"-"`
	App          *fiber.App   `yaml:"-"`
	CliApp       *cli.App     `yaml:"-"`
	SuperUid     int          `yaml:"superUid"`
	AppConfig    AppConfig    `yaml:"app"`
}

var userConfig *Config

func init() {
	configFilePath := "./config/config.yaml"
	configFileBytes, err := ioutil.ReadFile(configFilePath)
	if err != nil {
		panic("配置文件不存在，配置文件文件夹应该在当前运行目录中。")
	}

	userConfig = &Config{}

	err = yaml.Unmarshal(configFileBytes, userConfig)
	if err != nil {
		panic(err.Error())
	}

	// 判断 port
	serverConfig := userConfig.ServerConfig
	if serverConfig.Port == "" {
		panic("请输入服务端口号")
	}
}

func GetConfig() *Config {
	return userConfig
}

func AddStartServeFunc(beforeFunc BeforeStartServeFunc) {
	userConfig.AppConfig.BeforeStartServe = beforeFunc
}
